// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

package client;

import ocsf.client.*;
import common.*;
import java.io.*;
import java.util.Observable;
import java.util.Observer;

/**
 * This class overrides some of the methods defined in the abstract
 * superclass in order to give more functionality to the client.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;
 * @author Fran&ccedil;ois B&eacute;langer
 * @version July 2000
 */
public class ChatClient implements Observer
{
  //Instance variables **********************************************
  
  /**
   * The interface type variable.  It allows the implementation of 
   * the display method in the client.
   */
  ChatIF clientUI; 

	/**
	 * Chap6 Florent & Mejdi:
	 * au lieu d'heriter de AbstractClient, on déclare
	 * un ObservableClient
	 * 
	 * les méthodes de ObservableClient sont donc
	 * appelées avec observedClient.methode()
	 * au lieu de super.methode()
	 */
  ObservableClient observedClient;
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the chat client.
   *
   * @param host The server to connect to.
   * @param port The port number to connect on.
   * @param clientUI The interface type variable.
   */
  public ChatClient(String host, int port, ChatIF clientUI) 
    throws IOException 
  {
	// Chap6: instantiation de ObservableClient
    this.observedClient = new ObservableClient(host, port);
	// Chap6: enregistrement du client en tant qu'observeur (du serveur)
    observedClient.addObserver( this );
    
    this.clientUI = clientUI;
    observedClient.openConnection();
  }

  
  //Instance methods ************************************************
    
  /**
   * This method handles all data that comes in from the server.
   *
   * @param msg The message from the server.
   */
  public void handleMessageFromServer(Object msg ) 
  {
    clientUI.display("Message received : " + msg.toString());
  }

  /**
   * This method handles all data coming from the UI            
   *
   * @param message The message from the UI.    
   */
  public void handleMessageFromClientUI(String message)
  {
    try
    {
    	observedClient.sendToServer(message);
    }
    catch(IOException e)
    {
      clientUI.display
        ("Could not send message to server.  Terminating client.");
      quit();
    }
  }
  
  /**
   * This method terminates the client.
   */
  public void quit()
  {
    try
    {
    	observedClient.closeConnection();
    }
    catch(IOException e) {}
    System.exit(0);
  }


	protected void connectionException(Exception exception) {
		// TODO Auto-generated method stub
		clientUI.display
	    ("Server not responding.");
		this.quit();
	}
	
	
	protected void connectionClosed() {
		// TODO Auto-generated method stub
		clientUI.display
	    ("Connection closed.  Terminating clients.");
		
	}
	
	
	protected void connectionEstablished() {
		// TODO Auto-generated method stub
		clientUI.display
	    ("Connection established.");
		
	}
	
	
	/**
	 * Chap6 Florent & Mejdi:
	 * update() est appelé automatiquement pour déclencher des actions,
	 * quand les serveurs appellent la méthode notifyObservers()
	 * 
	 * Il faut donc traiter ce qu'on recoit pour savoir ce que c'est
	 * message de connection / exception / commande ...
	 */
	@Override
	public void update(Observable o, Object arg) {
		//ObservableServer server = (ObservableServer) o;
		
		if ( o == observedClient ) {
	
			if ( arg instanceof String ) {
				if ( arg == observedClient.CONNECTION_CLOSED )
					connectionClosed();
				else if ( arg == observedClient.CONNECTION_ESTABLISHED )
					connectionEstablished();
				else
					handleMessageFromServer( arg );
				
			} else if ( arg instanceof Exception ) {
				connectionException( (Exception)arg );
			}
			
		}
	}
  
  
}
//End of ChatClient class
